package cn.zhouchao.basic.controller;

import cn.zhouchao.basic.util.AjaxResult;
import cn.zhouchao.basic.util.FastdfsUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastdfsController {
    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart MultipartFile file) throws IOException {
        //获取全路径
        String filename = file.getOriginalFilename();//定义MultipartFile接口类对象 file,获取文件名
        String extension = FilenameUtils.getExtension(filename); //使用FilenameUtils工具类，获取扩展名
        String path = FastdfsUtil.upload(file.getBytes(), extension);//通过上传方法获取到路径
        return AjaxResult.me().success(path);//返回路径到前端，用于在前端展示
    }

    /**
     * 删除
     * @param path
     * @return
     * @throws IOException
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam(value = "path",required = true) String path) throws IOException {
        //1.获取组名
        String groupTmp = path.substring(1);
        String groupName = groupTmp.substring(0, groupTmp.indexOf("/"));
        //2.获取路径
        String substring = groupTmp.substring(groupTmp.indexOf("/") + 1);
        //3.调用工具进行删除
        FastdfsUtil.delete(groupName,substring);
        return AjaxResult.me().success(path);
    }

}
